require("./common/extend");
let createError = require("http-errors");
let express = require("express");
let path = require("path");
let logger = require("morgan");
let cors = require("cors");
let domain = require('domain');

let whiteListFun = require("./config/whiteList");
// redis 相关
let cookieParser = require("cookie-parser");
let session = require("express-session");

global.redis = require("./config/redis");
// end
const indexRouter = require("./routes/index.router");
let app = express();
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
//注册
app.use(cookieParser());
app.use(
  session({
    secret: "keyboard keep",
    saveUninitialized: false,
    resave: false,
    cookie: { maxAge: 31 * 24 * 60 * 60 * 1000 } //默认1小时
  })
);
app.use(logger("dev"));
app.use(cors()); //开启跨域
app.use(express.json({ limit: "5mb" }));
app.use(
  express.urlencoded({
    extended: false,
    limit: "50mb",
    parameterLimit: 1000000
  })
);
app.use(express.static(path.join(__dirname, "public")));

app.use(async function (req, res, next) {
  // console.log("client ip=>" + tool.getClientIp(req));
  // if (!whiteListFun(req.path)) {
  //   let { success, msg } = await tool.validateToken(req.headers.token);
  //   if (!success) {
  //     tool.rError(res, {
  //       code: 401,
  //       msg: msg
  //     });
  //     return;
  //   }
  //   msg && (req.body.sys_id = msg.id);//赋值该用户系统id
  // };
  next();
});
indexRouter.install(app); //注册路由

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  console.log(req.url);
  if(req.url=="/favicon.ico"){
    next();    
  }else{
    next(createError(404));
  }
});

/*
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});
*/
// 使用 domain 来捕获大部分异常
app.use(function (req, res, next) {
  var reqDomain = domain.create();
  reqDomain.on('error', function () {
    try {
      var killTimer = setTimeout(function () {
        process.exit(1);
      }, 30000);
      killTimer.unref();
      app.close();
      res.send(500);
    } catch (e) {
      console.error('error when exit', e.stack);
    }
  });
  reqDomain.run(next);
});

// uncaughtException 避免程序崩溃
process.on('uncaughtException', function (err) {
  console.error("致命错误-->",err);
  try {
    var killTimer = setTimeout(function () {
      process.exit(1);
    }, 30000);
    killTimer.unref();
  } catch (e) {
    console.log('error when exit', e.stack);
  }
});
module.exports = app;
